const ajax = require('../../utils/ajax/ajax.js')
const util = require('../../utils/util.js')
Page({
    data: {
        phone: '',
        code: '',
        timeText: '获取验证码',
        timer: '', // 定时器
        count: 60
    },

    inputPhone(e) {
        this.setData({
            phone: e.detail.value
        })
    },

    // 赋值 code
    inputCode(e) {
        this.setData({
            code: e.detail.value
        })
    },
    // 验证码倒计时
    getCode() {
        const that = this
        let {
            phone,
            timer,
            count
        } = that.data

        const reg_phone = /^1[3456789]\d{9}$/;
        if (!reg_phone.test(phone)) {
            util.toast('手机号格式错误')
            return
        }

        const TIME_COUNT = 60
        timer = setInterval(() => {
            if (count > 0 && count <= TIME_COUNT) {
                that.setData({
                    timeText: `重新获取(${count--}s)`,
                })
            } else {
                clearInterval(timer)
                that.setData({
                    timeText: '获取验证码',
                })
            }
        }, 1000)
        that.getCodeAjax()
    },
    // 发送验证码
    getCodeAjax() {
        const that = this
        ajax.post({
            url: '/wx/sendSms',
            data: {
                phone: that.data.phone
            },
            success(res) {
                util.toast(res.msg)
            },
            fail(err) {
                util.toast(err.msg)
            }
        })
    },
    // 登录
    login() {
        const that = this
        const {
            phone,
            code
        } = that.data
        if (!phone) {
            util.toast('手机号有误')
            return
        }
        if (code.length !== 6) {
            util.toast('验证码有误')
            return
        }
        ajax.post({
            url: '/wx/login',
            data: {
                phone: phone,
                verify_code: code,
                openid: wx.getStorageSync('openid')
            },
            success(res) {
                wx.setStorageSync('token', res.data.token)
                let pages = getCurrentPages()
                pages.forEach(item => {
                    typeof item.onUserLogin === 'function' && item.onUserLogin()
                })
                wx.switchTab({
                    url: '/pages/Index/index/index',
                })
            },
            fail(err) {
                util.toast(err.msg)
            }
        })
    }
})